package eu.codlab.twitteirb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Iterator;
import java.util.Set;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public final class LoginManager {
	private String _login;
	private String _password;
	private TwittEirbService _master;
	private Context _context;
	private String _last;
	private CookieManager _cookie;


	private LoginManager(){
		_last = null;
		setLogin("","");
	}

	protected void setLogin(String login, String password){
		_login = login;
		_password = password;
	}

	public LoginManager(Context context,TwittEirbService master, CookieManager cookie){
		this();
		_master = master;
		_cookie = cookie;
		_context = context;
	}
	
	public void log(String i1, String i2){
		//Log.d(i1,i2);
	}

	private final class MessageAsync extends AsyncTask<String, Object, Object>{
		public MessageAsync(){
		}

		@Override
		protected Integer doInBackground(String... arg0) {
			String [] services = new String[]{"twitt.eirb.fr","trombi-dev.eirb.fr"};
			log("LoginManager","beggining login in...");

			AccountManager am = AccountManager.get(_context);
			Account[] aca = am.getAccountsByType(AuthenticatorHelper.ACCOUNT_TYPE);
			if(aca.length>0){
				//we have an account \o/
				log("LoginManager","we have an account \\o/");
				Account compte = aca[0];
				String type = compte.type;
				String username = compte.name;
				Bundle options = new Bundle();
				options.putStringArray("services", services);
				/** this part IS AWFUL !!!!*/
				type="";
				type=services[0];
				for(int i=1;i<services.length;i++)
					type+=";"+services[i];
				log("LoginManager","requesting "+type);
				AccountManagerFuture<Bundle> res = am.getAuthToken (compte, type, false, null, null);
				//should be >> nicer ;)
				//but did not work for @yodin >> shame on his phone :p
				//AccountManagerFuture<Bundle> res = am.getAuthToken(compte, type, options, null, null, null);
				log("LoginManager","waiting for authtoken");
				Bundle b = null;
				try {
					b = res.getResult();
				} catch (Exception e) {
					e.printStackTrace();
				}
				Set<String> keys = b.keySet();
				Iterator<String> ke = keys.iterator();
				log("LoginManager","obtained authtoken");

				if(b != null && b.containsKey(AccountManager.KEY_INTENT)){
					log("LoginManager","obtained intent \\o/");
					Intent i = b.getParcelable(AccountManager.KEY_INTENT);
					if(i.hasExtra("services")){
						log("LoginManager","obtained services \\o/");
						String [] r = i.getStringArrayExtra("services");
						if(r != null && r.length == 2){
							_login = username;
							_master.onLoginOK(r[0], r[1]);
							return null;
						}
					}
				}
				log("LoginManager","hum error :(");

				_master.onLoginError();
			}
			log("LoginManager","login the normal way... /o\\");

			AuthenticatorHelper helper = new AuthenticatorHelper();
			String res [] = helper.infos(_login, _password, services);

			if(res == null){
				_master.onLoginError();
			}else{
				_master.onLoginOK(res[0], res[1]);
			}
			return null;
		}
	}

	public void go(){
		URL url=null;
		try {

			MessageAsync m = new MessageAsync();
			String[] u = new String[1];
			u[0]="http://auth.eirb.fr/login";
			m.execute(u);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String readStream(InputStream in) throws IOException {  
		StringBuilder sb = new StringBuilder();  
		BufferedReader r = new BufferedReader(new InputStreamReader(in),2048);  
		for (String line = r.readLine(); line != null; line =r.readLine()){  
			sb.append(line);  
		}  
		in.close();  
		return sb.toString();  
	}   

	public String getLogin(){
		return _login;
	}

}
